extends Node2D

# 控件
onready var hand_region = get_node("HandRegion")
onready var big_card_container = get_node("BigCardContainer")
onready var deck = get_node("Deck")
onready var states_holder = get_node("GameStates")
onready var desk = get_node("Desk")

# 状态机
const BASIC_STATES_PATH: String = 'res://Game/Controllers/States'
const DEFAULT_STATE_NAME: String = 'setup'

var states_map: Dictionary = {}
var states_stack: Array = []

signal state_changed


func _ready() -> void:
    # 根据屏幕调整位置
    var size: Vector2 = get_viewport().get_size()
    hand_region.set_position(Vector2(size.x / 2, size.y - hand_region.HAND_REGION_HEIGHT))

    big_card_container.set_position(Vector2(200, 300))
    big_card_container.set_hand_region(hand_region)

    _load_packages()

    set_process(true)
    pass

func _load_packages() -> void:
    _load_states()
    _load_cards()
    pass

func _load_states() -> void:
    # 加载基本规则
    var script_names: Array = []
    Utilities.get_files_in_directory(BASIC_STATES_PATH, true, script_names, Utilities.FILE_FORMAT_PACKED_SCENE)
    for script in script_names:
        print(script)
        var new_state: State = load(script).instance()
        var name: String = script.get_file().trim_suffix(Utilities.FILE_FORMAT_PACKED_SCENE)
        states_map[name] = new_state
        new_state.connect('complete', self, '_on_state_completed')
        new_state.connect('suspend', self, '_on_state_suspended')
        states_holder.add_child(new_state)
    pass

func _load_cards() -> void:
    pass

func _process(delta: float) -> void:
    if states_stack.size() > 0:
        states_stack[0].update(delta)
    else:
        states_stack.push_front(states_map[DEFAULT_STATE_NAME])
        states_stack[0].enter([])
    pass

func _on_state_completed(next: String, params: Array) -> void:
    var ls: State = states_stack[0]
    ls.exit()

    if next == '':
        states_stack.pop_front()
    else:
        states_stack[0] = states_map[next]

    emit_signal("state_changed", ls, states_stack[0])

    if next != '':
        states_stack[0].enter(params)
    pass

func _on_state_suspended(next: String, params: Array) -> void:
    var ns: State = states_map[next]
    if ns != null:
        var ls: State = states_stack[0]
        ls.exit()

        states_stack.push_front(ns)
        emit_signal("state_changed", ls, ns)
        ns.enter(params)
    pass
